use ruma::{
    api::client::{config::get_global_account_data, error::ErrorKind},
    events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent},
    serde::Raw,
};
use serde::Deserialize;
use serde_json::value::RawValue;

use crate::{server::server, Error, Result, Ruma};

/// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}`
///
/// Gets some account data for the sender user.
pub async fn get_global_account_data_route(
    body: Ruma<get_global_account_data::v3::Request>,
) -> Result<get_global_account_data::v3::Response> {
    let sender_user = body.sender_user.as_ref().expect("user is authenticated");

    let event: Box<RawValue> = server()
        .account
        .get(None, sender_user, &body.event_type.to_string().into())?
        .ok_or_else(|| Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;

    let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
        .map_err(|_| Error::bad_database("Invalid account data event in db."))?
        .content;

    Ok(get_global_account_data::v3::Response { account_data })
}

#[derive(Deserialize)]
struct ExtractRoomEventContent {
    _content: Raw<AnyRoomAccountDataEventContent>,
}

#[derive(Deserialize)]
struct ExtractGlobalEventContent {
    content: Raw<AnyGlobalAccountDataEventContent>,
}
